import { loginFace } from '../interface/req'
import { setCookie } from "../utils/cookie";

const qs = require('qs')

// 生成随机token
function randomStr(len: number = 50) {
    var str = ''
    var dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-'
    for (var i = 0; i < len; i++) {
        var index = Math.floor(Math.random() * dict.length)
        str += dict[index]
    }
    return str
}

const loginInterface = (req: loginFace) => {
    const { email, password } = qs.parse(req.url.split('?')[1])
    console.log('登录 传递参数', email, password)

    const registerList: any = localStorage.getItem('register_list') || []
    let code: number = 401, msg: string = '账号不存在 或 密码错误，请检查后重试',
        data: any = {}

    if (registerList && registerList.length !== 0) {
        const list = JSON.parse(registerList)
        let bool = list.findIndex((item: any) => item.email == email && item.password == password)
        if (bool > -1) {
            code = 0, msg = 'success',
                data = {
                    date: Date.now(),
                    token: randomStr()
                }
        }
    }


    // 登录成功 种cookie信息
    if (code == 0 && msg == 'success') {
        setCookie(data.token, data.date);
    }

    return {
        code,
        msg,
        data
    }
}

export default loginInterface 